CONTENTS

Chapter 12. XML

The preface of the book Essential XML by Don Box, et al. [Addison-Wesley 2000] states only half-jokingly: "The Extensible Markup Language (XML) has replaced Java, Design Patterns, and Object Technology as the software industry's solution to world hunger." Indeed, as you will see in this chapter, XML is a very useful technology for describing structured information. XML tools make it easy to process and transform that information. But XML is not a silver bullet. You need domain-specific standards and code libraries to use it effectively. Moreover, far from making Java obsolete, XML and Java work very well together. Essentially all important XML libraries have been implemented first in Java, and many of them are unavailable in any other programming language. Since the late 1990s, IBM, Apache, and others have been instrumental in producing high-quality Java libraries for XML processing. Starting with SDK 1.4, Sun has integrated the most important libraries into the Java 2 Platform, Standard Edition.

NOTE

graphics/note.gif
 

You can download the Java API for XML Processing (JAXP) library from http://java.sun.com/xml to add the same XML processing capabilities to older Java installations.

This chapter gives an introduction into XML and covers the XML features of SDK 1.4. As always, we will point out along the way when the hype surrounding XML is justified, and when you have to take it with a grain of salt and solve your problems the old-fashioned way, through good design and code.

An Introduction to XML

You have seen several examples of property files to describe the configuration of a program, for example in Chapters 2 and 4. A property file contains a set of name/value pairs, such as

fontname=Times Roman
fontsize=12
windowsize=400 200
color=0 50 100

You can use the Properties class to read in such a file with a single method call. That's a nice feature, but it doesn't really go far enough. In many cases, the information that you want to describe has more structure than the property file format can comfortably handle. For example, consider the fontname/fontsize entries in the example. It would be more object-oriented to have a single entry:

font=Times Roman 12

But then parsing the font description gets ugly—you have to figure out when the font name ends and when the font size starts.

Property files have a single flat hierarchy. You can often see programmers work around that limitation with key names such as

title.fontname=Helvetica
title.fontsize=36
body.fontname=Times Roman
body.fontsize=12

Another shortcoming of the property file format is caused by the fact that keys have to be unique. To store a sequence of values, you need another workaround, such as

menu.item.1=Times Roman
menu.item.2=Helvetica
menu.item.3=Goudy Old Style

The XML format solves these problems because it can express hierarchical structures, which is more flexible than the flat table structure of a property file.

An XML file for describing a program configuration might look like this:

<configuration>
   <title>
      <font>
         <name>Helvetica</name>
         <size>36</size>
      </font>
   </title>
   <body>
         <name>Times Roman</name>
         <size>12</size>
   </body>
   <window>
      <width>400</width>
      <height>200</height>
   </window>
   <color>
      <red>0</red>
      <green>50</green>
      <blue>100</blue>
   </color>
   <menu>
      <item>Times Roman</item>
      <item>Helvetica</item>
      <item>Goudy Old Style</item>
   </menu>
</configuration>

The XML format allows you to express the structure hierarchy and repeated elements without contortions.

As you can see, the format of an XML file is very straightforward. It looks very similar to an HTML file. There is a good reason—both the XML and HTML formats are descendants of the venerable Standard Generalized Markup Language (SGML).

SGML has been around since the 1970s for describing the structure of complex documents. It has been used with good success in some industries that require ongoing maintenance of massive documentation, in particular the aircraft industry. But SGML is quite complex, so it has never caught on in a big way. Much of that complexity arises from the fact that SGML has two conflicting goals. SGML wants to make sure that documents are formed according to the rules for their document type. But it also wants to make data entry easy by allowing shortcuts that reduce typing. XML was designed as a simplified version of SGML for use on the Internet. As is often true, simpler is better, and XML has enjoyed the immediate and enthusiastic reception that has eluded SGML for so long.

NOTE

graphics/note.gif
 

You can find a very nice version of the XML standard, with annotations by Tim Bray, at http://www.xml.com/axml/axml.html.

Even though XML and HTML have common roots, there are important differences between the two.

NOTE

graphics/note.gif
 

The current recommendation for web documents by the World Wide Web Consortium (W3C) is the XHTML standard, which tightens up the HTML standard to be XML compliant. You can find a copy of the XHTML standard at http://www.w3.org/TR/xhtml1/. XHTML is backwards-compatible with current browsers, but unfortunately many current HTML authoring tools do not yet support it. Once XHTML becomes more widespread, you can use the XML tools that are described in this chapter to analyze web documents.

The Structure of an XML Document

An XML document should start with a header such as

<?xml version="1.0"?>

or

<?xml version="1.0" encoding="UTF-8"?>

Strictly speaking, a header is optional, but it is highly recommended.

NOTE

graphics/note.gif
 

Because SGML was created for processing of real documents, XML files are called documents, even though most XML files describe data sets that one would not normally call documents.

The header is normally followed by a document type declaration, such as

<!DOCTYPE web-app PUBLIC
   "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
   "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

Document type declarations are an important mechanism to ensure the correctness of a document, but they are not required. We will discuss them later in this chapter.

Finally, the body of the XML document contains the root element, which can contain other elements. For example,

<?xml version="1.0"?>
<!DOCTYPE configuration . . .>
<configuration>
   <title>
      <font>
         <name>Helvetica</name>
         <size>36</size>
      </font>
   </title>
   . . .
</configuration>

An element can contain child elements, text, or both. In the example above, the font element has two child elements, name and size. The name element contains the text "Helvetica".

TIP

graphics/tip.gif
 

It is best if you structure your XML documents such that an element contains either child elements or text. In other words, you should avoid situations such as

<font>
   Helvetica
   <size>36</size>
</font>

This is called mixed contents in the XML specification. As you will see later in this chapter, you can design much cleaner document type definitions if you avoid mixed contents.

XML elements can contain attributes, such as

<size unit="pt">36</size>

There is some disagreement among XML designers about when to use elements and when to use attributes. For example, it would seem easier to describe a font as

<font name="Helvetica" size="36"/>

than

<font>
   <name>Helvetica</name>
   <size>36</size>
</font>

However, attributes are much less flexible. Suppose you want to add units to the size value. If you use attributes, then you have to add the unit to the attribute value:

<font name="Helvetica" size="36 pt"/>

Ugh! Now you have to parse the string "36 pt", just the kind of hassle that XML was designed to avoid. Adding an attribute to the size element is much cleaner:

<font>
   <name>Helvetica</name>
   <size unit="pt">36</size>
</font>

A commonly used rule of thumb is that attributes should only be used when they modify the interpretation of a value, not to specify values. If you find yourself engaged in metaphysical discussions about whether a particular setting is a modification of the interpretation of a value or not, then just say "no" to attributes and use elements throughout. Many useful DTDs don't use attributes at all.

NOTE

graphics/note.gif
 

In HTML, the rule for attribute usage is simple: If it isn't displayed on the web page, it's an attribute. For example, consider a hyperlink

<a href="http://java.sun.com">Java Technology</a>

The string Java Technology is displayed on the web page, but the URL of the link is not a part of the displayed page. However, that rule isn't all that helpful for most XML files since the data in an XML file isn't normally meant to be viewed by humans.

Elements and text are the "bread and butter" of XML documents. There are a few other markup instructions that you may encounter.

Parsing an XML Document

To process an XML document, you need to parse it. A parser is a program that reads a file, confirms that the file has the correct format, breaks it up into the constituent elements, and lets a programmer access those elements. There are two kinds of XML parsers:

The DOM parser is easier to use for most purposes, and we will explain it first.

You would want to consider the SAX parser if you process very long documents whose tree structures would use up a lot of memory, or if you are just interested in a few elements and you don't care about their context.

The DOM parser interface is standardized by the World Wide Web Consortium (W3C). The org.w3c.dom package contains the definitions of interface types such as Document and Element. Different suppliers, such as the Apache Organization and IBM, have written DOM parsers whose classes implement these interfaces. The Sun Java API for XML Processing (JAXP) library actually makes it possible to plug in any of these parsers. But Sun also includes its own DOM parser in the Java SDK. We'll use the Sun parser in this chapter.

To read an XML document, you need a DocumentBuilder object which you get from a DocumentBuilderFactory, like this:

DocumentBuilderFactory factory
   = DocumentBuilderFactory.newInstance();
DocumentBuilder builder
   = factory.newDocumentBuilder();

You can now read a document from a file:

File f = . . .
Document doc = builder.parse(f);

Alternatively, you can use an URL:

URL u = . . .
Document doc = builder.parse(u);

You can even specify an arbitrary input stream:

InputStream in = . . .
Document doc = builder.parse(in);

NOTE

graphics/note.gif
 

If you use an input stream as an input source, then the parser will not be able to locate other files that are referenced relative to the location of the document, such as a DTD in the same directory. You can install an "entity resolver" to overcome that problem. But it is usually easier to just use a file or URL than an input stream.

The Document object is an in-memory representation of the tree structure of the XML document. It is composed of objects whose classes implement the Node interface and its various subinterfaces. Figure 12-1 shows the inheritance hierarchy of the subinterfaces.

Figure 12-1. The Node interfaces and its subinterfaces

graphics/12fig01.gif

You start analyzing the contents of a document by calling the getDocumentElement method. It returns the root element.

Element root = doc.getDocumentElement();

For example, if you are processing a document

<?xml version="1.0"?>
<font>
   . . .
</font>

then calling getDocumentElement returns the font element.

The getTagName method returns the tag name of an element. For example, in the preceding example, root.getTagName() returns the string "font".

To get the element's children (which may be subelements, text, comments, or other nodes), use the getChildNodes method. That method returns a collection of type NodeList. That type was invented before the standard Java collections, and it has a different access protocol. The item method gets the item with a given index, and the getLength method gives the total count of the items. Therefore, you can enumerate all children like this:

NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
   Node child = children.item(i);
   . . .
}

You have to be careful when analyzing the children. Suppose for example that you are processing the document

<font>
   <name>Helvetica</name>
   <size>36</size>
</font>

You would expect the font element to have two children, but the parser reports five:

Figure 12-2 shows the DOM tree.

Figure 12-2. A Simple DOM Tree

graphics/12fig02.gif
 

If you only expect subelements, then you can ignore the whitespace:

for (int i = 0; i < children.getLength(); i++)
{
   Node child = children.item(i);
   if (child instanceof Element)
   {
      Element childElement = (Element)child;
      . . .
   }
}

Now you only look at two elements, with tag names name and size.

As you will see in the next section, you can do even better if your document has a document type declaration. Then the parser knows which elements don't have text nodes as children, and it can suppress the whitespace for you.

When analyzing the name and size elements, you want to retrieve the text strings that they contain. Those text strings are themselves contained in child nodes of type Text. Since you know that these Text nodes are the only children, you can use the getFirstChild method without having to traverse another NodeList. Then use the getData method to retrieve the string stored in the Text node.

for (int i = 0; i < children.getLength(); i++)
{
   Node child = children.item(i);
   if (child instanceof Element)
   {
      Element childElement = (Element)child;
      Text textNode = childElement.getFirstChild();
      String text = textNode.getData().trim();
      if (childElement.getTagName().equals("name"))
         name = text;
      else if (childElement.getTagName().equals("size"))
         size = Integer.parseInt(text);
   }
}

TIP

graphics/tip.gif
 

It is a good idea to call trim on the return value of the getData method. If the author of an XML file puts the beginning and the ending tag on separate lines, such as

<size>
   36
</size>

then the parser includes all line breaks and spaces in the text node data. Calling the trim method removes the whitespace surrounding the actual data.

You can also get the last child with the getLastChild, and the next sibling of a node with getNextSibling. Therefore, another way of traversing a set of child nodes is

for (Node childNode = element.getFirstChild();
   childNode != null;
   childNode = childNode.getNextSibling())
{
   . . .
}

NOTE

graphics/note.gif
 

It is rather tedious to search for nodes in an XML tree by looking at the root, its children, grandchildren, and so on. The XPath technology simplifies searches. For example, you can locate the node with the path /configuration/title/font/name with a single method call. However, XPath is not yet a part of the XML library in the Java platform. You can find out the XPath specification at http://www.w3.org/TR/xpath. The Xalan library from the Apache group contains an implementation of XPath; see http://xml.apache.org/xalan-j/overview.html.

To enumerate the attributes of a node, call the getAttributes method. It returns a NamedNodeMap object which contains Node objects that describe the attributes. You can traverse the nodes in a NamedNodeMap in the same way as a NodeList. Then call the getNodeName and getNodeValue methods to get the attribute names and values.

NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++)
{
   Node attribute = attributes.item(i);
   String name = attribute.getNodeName();
   String value = attribute.getNodeValue();
   . . .
}

Alternatively, if you know the name of an attribute, you can retrieve the corresponding value directly:

String unit = element.getAttribute("unit");

You have now seen how to analyze a DOM tree. The program in Example 12-1 puts these techniques to work. You can use the File -> Open menu option to read in an XML file. A DocumentBuilder object parses the XML file and produces a Document object. The program displays the Document object as a JTree (see Figure 12-3).

Figure 12-3. A parse tree of an XML document

graphics/12fig03.gif
 

The tree display shows clearly how child elements are surrounded by text containing whitespace and comments. For greater clarity, the program displays newline and return characters as \n and \r. (Otherwise, they would show up as hollow boxes, the default symbol for a character that Swing cannot draw in a string.)

If you followed the section on trees in Chapter 6, you will recognize the techniques that this program uses to display the tree. The DOMTreeModel class implements the TreeModel interface. The getRoot method returns the root element of the document. The getChild method gets the node list of children and returns the item with the requested index. However, the tree model returns DOM Node objects whose toString methods aren't necessarily descriptive. Therefore, the program installs a tree cell renderer that extends the default cell renderer and sets the label text to a more descriptive form. The cell renderer displays the following:

If you need to analyze XML documents that contain other node types (such as processing instructions), then you can enhance the program accordingly. The purpose of the program is not to be a polished XML viewer—there are many slicker programs available—but to show you how to analyze and enumerate the children and attributes of DOM tree nodes.

NOTE

graphics/note.gif
 

You can get a very nice free XML viewer from IBM AlphaWorks at http://www.alphaworks.ibm.com/tech/xmlviewer.

Example 12-1 DOMTreeTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import javax.swing.*;
  5. import javax.swing.event.*;
  6. import javax.swing.tree.*;
  7. import javax.xml.parsers.*;
  8. import org.w3c.dom.*;
  9. import org.xml.sax.*;
 10.
 11. /**
 12.    This program displays an XML document as a tree.
 13. */
 14. public class DOMTreeTest
 15. {
 16.    public static void main(String[] args)
 17.    {
 18.       JFrame frame = new DOMTreeFrame();
 19.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 20.       frame.show();
 21.    }
 22. }
 23.
 24. /**
 25.    This frame contains a tree that displays the contents of
 26.    an XML document.
 27. */
 28. class DOMTreeFrame extends JFrame
 29. {
 30.    public DOMTreeFrame()
 31.    {
 32.       setTitle("DOMTreeTest");
 33.       setSize(WIDTH, HEIGHT);
 34.
 35.       JMenu fileMenu = new JMenu("File");
 36.       JMenuItem openItem = new JMenuItem("Open");
 37.       openItem.addActionListener(new
 38.          ActionListener()
 39.          {
 40.             public void actionPerformed(ActionEvent event)
 41.             {
 42.                openFile();
 43.             }
 44.          });
 45.       fileMenu.add(openItem);
 46.
 47.       JMenuItem exitItem = new JMenuItem("Exit");
 48.       exitItem.addActionListener(new
 49.          ActionListener()
 50.          {
 51.             public void actionPerformed(ActionEvent event)
 52.             {
 53.                System.exit(0);
 54.             }
 55.          });
 56.       fileMenu.add(exitItem);
 57.
 58.       JMenuBar menuBar = new JMenuBar();
 59.       menuBar.add(fileMenu);
 60.       setJMenuBar(menuBar);
 61.    }
 62.
 63.    /**
 64.       Open a file and load the document.
 65.    */
 66.    public void openFile()
 67.    {
 68.       JFileChooser chooser = new JFileChooser();
 69.       chooser.setCurrentDirectory(new File("."));
 70.
 71.       chooser.setFileFilter(new
 72.          javax.swing.filechooser.FileFilter()
 73.          {
 74.             public boolean accept(File f)
 75.             {
 76.                return f.isDirectory()
 77.                   || f.getName().toLowerCase().endsWith(".xml");
 78.             }
 79.             public String getDescription()
 80.             {
 81.                return "XML files";
 82.             }
 83.          });
 84.       int r = chooser.showOpenDialog(this);
 85.       if (r != JFileChooser.APPROVE_OPTION) return;
 86.       File f = chooser.getSelectedFile();
 87.       try
 88.       {
 89.          if (builder == null)
 90.          {
 91.             DocumentBuilderFactory factory
 92.                = DocumentBuilderFactory.newInstance();
 93.             builder = factory.newDocumentBuilder();
 94.          }
 95.
 96.          Document doc = builder.parse(f);
 97.          JTree tree = new JTree(new DOMTreeModel(doc));
 98.          tree.setCellRenderer(new DOMTreeCellRenderer());
 99.
100.          setContentPane(new JScrollPane(tree));
101.          validate();
102.       }
103.       catch (IOException exception)
104.       {
105.          JOptionPane.showMessageDialog(this, exception);
106.       }
107.       catch (ParserConfigurationException exception)
108.       {
109.          JOptionPane.showMessageDialog(this, exception);
110.       }
111.       catch (SAXException exception)
112.       {
113.          JOptionPane.showMessageDialog(this, exception);
114.       }
115.    }
116.
117.    private DocumentBuilder builder;
118.    private static final int WIDTH = 400;
119.    private static final int HEIGHT = 400;
120. }
121.
122. /**
123.    This tree model describes the tree structure of a Java
124.    object. Children are the objects that are stored in instance
125.    variables.
126. */
127. class DOMTreeModel implements TreeModel
128. {
129.    /**
130.       Constructs an empty tree.
131.    */
132.    public DOMTreeModel(Document aDoc)
133.    {
134.       doc = aDoc;
135.    }
136.
137.    public Object getRoot()
138.    {
139.       return doc.getDocumentElement();
140.    }
141.
142.    public int getChildCount(Object parent)
143.    {
144.       Node node = (Node)parent;
145.       NodeList list = node.getChildNodes();
146.       return list.getLength();
147.    }
148.
149.    public Object getChild(Object parent, int index)
150.    {
151.       Node node = (Node)parent;
152.       NodeList list = node.getChildNodes();
153.       return list.item(index);
154.    }
155.
156.    public int getIndexOfChild(Object parent, Object child)
157.    {
158.       Node node = (Node)parent;
159.       NodeList list = node.getChildNodes();
160.       for (int i = 0; i < list.getLength(); i++)
161.          if (getChild(node, i) == child)
162.             return i;
163.       return -1;
164.    }
165.
166.    public boolean isLeaf(Object node)
167.    {
168.       return getChildCount(node) == 0;
169.    }
170.
171.    public void valueForPathChanged(TreePath path,
172.       Object newValue) {}
173.
174.    public void addTreeModelListener(TreeModelListener l) {}
175.
176.    public void removeTreeModelListener(TreeModelListener l) {}
177.
178.    private Document doc;
179. }
180.
181. /**
182.    This class renders a class name either in plain or italic.
183.    Abstract classes are italic.
184. */
185. class DOMTreeCellRenderer extends DefaultTreeCellRenderer
186. {
187.    public Component getTreeCellRendererComponent(JTree tree,
188.       Object value, boolean selected, boolean expanded,
189.       boolean leaf, int row, boolean hasFocus)
190.    {
191.       super.getTreeCellRendererComponent(tree, value,
192.          selected, expanded, leaf, row, hasFocus);
193.       Node node = (Node)value;
194.       if (node instanceof Element)
195.          setText(elementString((Element)node));
196.       else if (node instanceof CharacterData)
197.          setText(characterString((CharacterData)node));
198.       else
199.          setText(node.getClass() + ": " + node.toString());
200.       return this;
201.    }
202.
203.    public static String elementString(Element e)
204.    {
205.       StringBuffer buffer = new StringBuffer();
206.       buffer.append("Element: <");
207.       buffer.append(e.getTagName());
208.       NamedNodeMap attributes = e.getAttributes();
209.       for (int i = 0; i < attributes.getLength(); i++)
210.       {
211.          buffer.append(' ');
212.          Node attributeNode = attributes.item(i);
213.          buffer.append(attributeNode.getNodeName());
214.          buffer.append('=');
215.          buffer.append('"');
216.          buffer.append(attributeNode.getNodeValue());
217.          buffer.append('"');
218.      }
219.      buffer.append('>');
220.      return buffer.toString();
221.    }
222.
223.    public static String characterString(CharacterData node)
224.    {
225.       StringBuffer buffer = new StringBuffer(node.getData());
226.       for (int i = 0; i < buffer.length(); i++)
227.       {
228.          if (buffer.charAt(i) == '\r')
229.          {
230.             buffer.replace(i, i + 1, "\\r");
231.             i++;
232.          }
233.          else if (buffer.charAt(i) == '\n')
234.          {
235.             buffer.replace(i, i + 1, "\\n");
236.             i++;
237.          }
238.          else if (buffer.charAt(i) == '\t')
239.          {
240.             buffer.replace(i, i + 1, "\\t");
241.             i++;
242.          }
243.       }
244.       if (node instanceof Text)
245.          buffer.insert(0, "Text: ");
246.       else if (node instanceof Comment)
247.          buffer.insert(0, "Comment: ");
248.       else if (node instanceof CDATASection)
249.          buffer.insert(0, "CDATASection: ");
250.
251.       return buffer.toString();
252.    }
253.}

javax.xml.parsers.DocumentBuilderFactory

graphics/api.gif
 

javax.xml.parsers.DocumentBuilder

graphics/api.gif
 

org.w3c.dom.Document

graphics/api.gif
 

org.w3c.dom.Element

graphics/api.gif
 

org.w3c.dom.Node

graphics/api.gif
 

org.w3c.dom.CharacterData

graphics/api.gif
 

org.w3c.dom.NodeList

graphics/api.gif
 

org.w3c.dom.NamedNodeMap

graphics/api.gif
 

Document Type Definitions

In the preceding section, you saw how to traverse the tree structure of a DOM document. However, if you simply follow that approach, you'll find that you are going to have quite a bit of tedious programming and error checking. Not only do you have to deal with whitespace between elements, but you also need to check whether the document contains the nodes that you expect. For example, suppose you are reading an element:

<font>
   <name>Helvetica</name>
   <size>36</size>
</font>

You get the first non-whitespace child. Then you need to check that its tag name is "name". You need to check that it has one child node of type Text. You move on to the next non-whitespace child and make the same check. What if the author of the document switched the order of the children, or added another child element? It is tedious to code all the error checking, and reckless to skip the checks.

Fortunately, one of the major benefits of an XML parser is that it can automatically verify that a document has the correct structure. Then the parsing becomes much simpler. For example, if you know that the font fragment has passed validation, then you can simply get the two grandchildren, cast them as Text nodes and get the text data, without any further checking.

To specify the document structure, you supply a document type definition (DTD). A DTD contains rules that explain how a document should be formed, by specifying the legal child elements and attributes for each element. For example, a DTD might contain a rule:

<!ELEMENT font (name,size)>

This rule expresses that a font element must always have two children, which are name and size elements.

It is not strictly a requirement for an XML document to use a DTD, but most serious uses of XML involve DTDs.

There are several methods for supplying a DTD. You can include a DTD in an XML document like this:

<?xml version="1.0"?>
<!DOCTYPE configuration [
   <!ELEMENT configuration . . .>
   more rules
   . . .
]>
<configuration>
  . . .
</configuration>

As you can see, the rules are included inside a DOCTYPE declaration, in a block delimited by [. . .]. The document type must match the name of the root element, such as configuration in our example.

Supplying a DTD inside an XML document is somewhat uncommon because DTDs can get lengthy. It makes more sense to store the DTD externally. The SYSTEM declaration can be used for that purpose. You specify a URL that contains the DTD, for example:

<!DOCTYPE configuration SYSTEM "config.dtd">

or

<!DOCTYPE configuration SYSTEM "http://myserver.com/config.dtd">

CAUTION

graphics/caution.gif
 

If you use a relative URL for the DTD (such as "config.dtd"), then you need to give the parser a File or URL object, not an InputStream. If you must parse from an input stream, supply an entity resolver—see the following note.

Finally, there is a mechanism for identifying "well-known" DTDs that has its origin in SGML. Here is an example:

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

If an XML processor knows how to locate the DTD with the public identifier, then it need not go to the URL.

NOTE

graphics/note.gif
 

If you use a DOM parser, and would like to support a PUBLIC identifier, call the setEntityResolver method of the DocumentBuilder class to install an object of a class that implements the EntityResolver interface. That interface has a single method, resolveEntity. Here is the outline of a typical implementation:

class MyEntityResolver implements EntityResolver
{
   public InputSource resolveEntity(String publicID,
      String systemID)
   {
      if (publicID.equals(a known ID))
         return new InputSource(DTD data);
      else
         return null; // use default behavior
   }
}

You can construct the input source from an InputStream, a Reader, or a string.

Now that you have seen how the parser locates the DTD, let us consider the various kinds of rules.

The ELEMENT rule specifies what children an element can have. You specify a regular expression, made up of the components shown in Table 12-1.

Here are several simple but typical examples. The following rule states that a menu element contains 0 or more item elements.

Table 12-1. Rules for Element Content
Rule Meaning
E* 0 or more occurrences of E
E+ 1 or more occurrences of E
E? 0 or 1 occurrences of E
E1|E2| . . . |En One of E1, E2, … , En
E1, E2, . . . , En E1 followed by E2, … , En
#PCDATA Text
(#PCDATA|E1|E2| . . . |En)* 0 or more occurrences of text and E1, E2, … ,En in any order (mixed content)
ANY Any children allowed
EMPTY No children allowed
<!ELEMENT menu (item)*>

This set of rules states that a font is described by a name followed by a size, each of which contain text.

<!ELEMENT font (name,size)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT size (#PCDATA)>

The abbreviation PCDATA denotes parsed character data. The data is called "parsed" because the parser interprets the text string, looking for < characters that denote the start of a new tag, or & characters that denote the start of an entity.

NOTE

graphics/note.gif
 

There is no way to express in a DTD that the text of the size element should be an integer. A newer specification, called XML Schema Definition (XSD), lets you specify the legal contents of a document with much greater precision. In XSD, the font specification can be expressed like this:

<xsd:complexType name="Font">
   <xsd:sequence>
      <xsd:element name="name" type="xsd:string"/>
      <xsd:element name="size" type="xsd:integer"/>
   </xsd:sequence>
</xsd:complexType>
<xsd:element name="font" type="Font"/>

You can find more information about the XML Schema specification at http://www.w3.org/XML/Schema. At this time, there is no support for the XML Schema technology in the Java SDK.

An element specification can contain regular expressions that are nested and complex. For example, here is a rule that describes the makeup of a chapter in this book:

<!ELEMENT chapter (intro,(heading,(para|image|table|note)+)+)

Each chapter starts with an introduction, which is followed by one or more sections consisting of a heading and one or more paragraphs, images, tables, or notes.

However, there is one common case when you can't define the rules to be as flexible as you might like. Whenever an element can contain text, then there are only two valid cases. Either the element contains nothing but text, such as

<!ELEMENT name (#PCDATA)>

Or the element contains any combination of text and tags in any order, such as

<!ELEMENT para (#PCDATA|em|strong|code)*>

It is not legal to specify other types of rules that contain #PCDATA. For example, the following rule is illegal:

<!ELEMENT captionedImage (image,#PCDATA)>

You have to rewrite such a rule, either by introducing another caption element, or by allowing any combination of image tags and text.

This restriction simplifies the job of the XML parser when parsing mixed content (a mixture of tags and text). Because you lose some control when allowing mixed content, it is best to design DTDs such that all elements contain either other elements or nothing but text.

NOTE

graphics/note.gif
 

Actually, it isn't quite true that you can specify arbitrary regular expressions of elements in a DTD rule. An XML parser may reject certain complex rule sets that lead to "non-deterministic" parsing. For example, a regular expression ((x,y)|(x,z)) is non-deterministic. When the parser sees x, it doesn't know which of the two alternatives to take. This expression can be rewritten in a deterministic form, as (x,(y|z)). However, there are some expressions that can't be reformulated, such as ((x,y)*|x?). The Sun parser gives no warnings when presented with an ambiguous DTD. It simply picks the first matching alternative when parsing, which causes it to reject some correct inputs. Of course, the parser is well within its rights to do so, since the XML standard allows a parser to assume that the DTD is unambiguous.

In practice, this isn't an issue over which you should lose sleep since most DTDs are so simple that you never run into ambiguity problems.

You also specify rules to describe the legal attributes of elements. The general syntax is

<!ATTLIST element attribute type default>

Table 12-2 shows the legal attribute types, and Table 12-3 shows the syntax for the defaults.

Table 12-2. Attribute types
Type Meaning
CDATA Any character string
(A1|A2| . . . |An) One of the string attributes A1 A2 . . . |An
NMTOKEN, NMTOKENS One or more name tokens
ID A unique ID
IDREF, IDREFS One or more references to a unique ID
ENTITY, ENTITIES One or more unparsed entities
Table 12-3. Attribute defaults
Default Meaning
#REQUIRED Attribute is required.
#IMPLIED Attribute is optional.
A Attribute is optional; the parser reports it to be A if it is not specified.
#FIXED A The attribute must either be unspecified or A; in either case, the parser reports it to be A.

Here are two typical attribute specifications:

<!ATTLIST font style (plain|bold|italic|bold-italic) plain>
<!ATTLIST size unit CDATA #IMPLIED>

The first specification describes the style attribute of a font element. There are four legal attribute values, and the default value is plain. The second specification expresses that the unit attribute of the size element can contain any character data sequence.

NOTE

graphics/note.gif
 

We generally recommend to use elements, not attributes, to describe data. Following that recommendation, the font style should be a separate element, such as <font><style>plain</style>...</font>. However, attributes have an undeniable advantage for enumerated types since the parser can verify that the values are legal. For example, if the font style is an attribute, the parser checks that it is one of the four allowed values, and it supplies a default if no value was given.

The handling of a CDATA attribute value is subtly different from the processing of #PCDATA that you have seen before, and quite unrelated to the <![CDATA[...] ]> sections. The attribute value is first normalized, that is, the parser processes character and entity references (such as &#233; or &lt;) and replaces whitespace with spaces.

An NMTOKEN (or name token) is similar to CDATA, but most non-alphanumeric characters and internal whitespace are disallowed, and the parser removes leading and trailing whitespace. NMTOKENS is a whitespace-separated list of name tokens.

The ID construct is quite useful. An ID is a name token that must be unique in the document—the parser checks the uniqueness. You will see an application in the next sample program. An IDREF is a reference to an ID that exists in the same document—which the parser also checks. IDREFS is a whitespace-separated list of ID references.

An ENTITY attribute value refers to an "unparsed external entity." That is a holdover from SGML that is rarely used in practice. The annotated XML specification at http://www.xml.com/axml/axml.html has an example.

A DTD can also define entities, or abbreviations that are replaced during parsing. You can find a good example for the use of entities in the user interface descriptions for the Mozilla/Netscape 6 browser. Those descriptions are formatted in XML and contain entity definitions such as

<!ENTITY back.label "Back">

Elsewhere, text can contain an entity reference, for example:

<menuitem label="&back.label;"/>

The parser replaces the entity reference with the replacement string. To internationalize the application, only the string in the entity definition needs to be changed. There are other uses of entities that are more complex and less commonly used. Look at the annotated XML specification for details.

This concludes the introduction to DTDs. Now that you have seen how to use DTDs, you can configure your parser to take advantage of them. First, tell the document builder factory to turn on validation.

factory.setValidating(true);

All builders produced by this factory will validate their input against a DTD. The most useful benefit of validation is to ignore whitespace in element content. For example, consider the XML fragment

<font>
   <name>Helvetica</name>
   <size>36</size>
</font>

A non-validating parser reports the whitespace between the font, name, and size elements because it has no way of knowing if the children of font are

(name,size)
(#PCDATA,name,size)*

or perhaps

ANY

Once the DTD specifies that the children are (name,size), the parser knows that the whitespace between them is not text. Call

factory.setIgnoringElementContentWhitespace(true);

and the builder will stop reporting the whitespace in text nodes. That means, you can now rely upon the fact that a font node has two children. You no longer need to program a tedious loop:

for (int i = 0; i < children.getLength(); i++)
{
   Node child = children.item(i);
   if (child instanceof Element)
   {
      Element childElement = (Element)child;
      if (childElement.getTagName().equals("name")) . . .
      else if (childElement.getTagName().equals("size")) . . .
  }
}

Instead, you can simply access the first and second child:

Element nameElement = (Element)children.item(0);
Element sizeElement = (Element)children.item(1);

That is why DTDs are so useful. You don't overload your program with rule checking code—the parser has already done that work by the time you get the document.

TIP

graphics/tip.gif
 

Many programmers who start using XML are uncomfortable with DTDs and end up analyzing the DOM tree on the fly. If you need to convince colleagues of the benefit of using DTDs, show them the two coding alternatives—it should win them over.

NOTE

graphics/note.gif
 

There is a danger in accessing children by their position in the node list.

If the DTD evolves, the list positions may change. Using the XPath technology, you can access tree elements in a more stable fashion by a path name, such as /configuration/title/font/name. However, XPath is not currently a part of the Java SDK.

When the parser reports an error, your application will want to do something about it—log it, show it to the user, or throw an exception to abandon the parsing.

Therefore, you should install an error handler whenever you use validation. Supply an object that implements the ErrorHandler interface. That interface has three methods:

void warning(SAXParseException exception)
void error(SAXParseException exception)
void fatalError(SAXParseException exception)

You install the error handler with the setErrorHandler method of the DocumentBuilder class:

builder.setErrorHandler(handler);

javax.xml.parsers.DocumentBuilder

graphics/api.gif
 

org.xml.sax.EntityResolver

graphics/api.gif
 

org.xml.sax.InputSource

graphics/api.gif
 

org.xml.sax.ErrorHandler

graphics/api.gif
 

org.xml.sax.SAXParseException

graphics/api.gif
 

javax.xml.parsers.DocumentBuilderFactory

graphics/api.gif
 

A Practical Example

In this section, we will work through a practical example that shows the use of XML in a realistic setting. Recall from Volume 1 Chapter 9 that the GridBagLayout is the most useful layout manager for Swing components. However, it is feared not just for its complexity but also for the programming tedium. It would be much more convenient to put the layout instructions into a text file instead of producing large amounts of repetitive code. In this section, you will see how to use XML to describe a grid bag layout, and how to parse the layout files.

A grid bag is made up of rows and columns, very similar to an HTML table. Similar to an HTML table, we'll describe it as a sequence of rows, each of which contains cells:

<gridbag>
   <row>
      <cell>...</cell>
      <cell>...</cell>
      . . .
    </row>
   <row>
      <cell>...</cell>
      <cell>...</cell>
      . . .
    </row>
   . . .
</gridbag>

The gridbag.dtd specifies these rules:

<!ELEMENT gridbag (row)*>
<!ELEMENT row (cell)*>

Some cells can span multiple rows and columns. In the grid bag layout, that is achieved by setting the gridwidth and gridheight constraints to values larger than 1. We will use attributes of the same name:

<cell gridwidth="2" gridheight="2">

Similarly, we will use attributes for the other grid bag constraints fill, anchor, gridx, gridy, weightx, weighty, ipadx, and ipady. (We don't handle the insets constraint because its value is not a simple type, but it would be straightforward to support it.) For example,

<cell fill="HORIZONTAL" anchor="NORTH">

For most of these attributes, we provide the same defaults as the GridBagConstraints default constructor:

<!ATTLIST cell gridwidth CDATA "1">
<!ATTLIST cell gridheight CDATA "1">
<!ATTLIST cell fill (NONE|BOTH|HORIZONTAL|VERTICAL) "NONE">
<!ATTLIST cell anchor (CENTER|NORTH|NORTHEAST|EAST
   |SOUTHEAST|SOUTH|SOUTHWEST|WEST|NORTHWEST) "CENTER">
<!ATTLIST cell ipadx CDATA "0">
<!ATTLIST cell ipady CDATA "0">

However, we use default weights of 100, which is more useful than the GridBagConstraints default of 0:

<!ATTLIST cell weightx CDATA "100">
<!ATTLIST cell weighty CDATA "100">

The gridx and gridy values get special treatment because it would be tedious and somewhat error-prone to specify them by hand. Supplying them is optional:

<!ATTLIST cell gridx CDATA #IMPLIED>
<!ATTLIST cell gridy CDATA #IMPLIED>

If they are not supplied, the program determines them according to the following heuristic: in column 0, the default gridx is 0. Otherwise, it is the preceding gridx plus the preceding gridwidth. The default gridy is always the same as the row number. Thus, you don't have to specify gridx and gridy in the most common cases, where a component spans multiple rows. But if a component spans multiple columns, then you need to specify gridx whenever you skip over that component.

NOTE

graphics/note.gif
 

Grid bag experts may wonder why we don't use the RELATIVE and REMAINDER mechanism to let the grid bag layout automatically determine the gridx and gridy positions. We tried, but no amount of fussing would produce the layout of the font dialog example of Volume 1. Reading through the GridBagLayout source code, it is apparent that the algorithm just won't do the heavy lifting that would be required to reliably find the appropriate positions.

The program parses the attributes and sets the grid bag constraints. For example, to read the grid width, the program contains a single statement:

constraints.gridwidth
   = Integer.parseInt(e.getAttribute("gridwidth"));

The program need not worry about a missing attribute since the parser automatically supplies the default value if no other value was specified in the document.

To test whether a gridx or gridy attribute was specified, we call the getAttribute method and check if it returns the empty string:

String value = e.getAttribute("gridy");
if (value.length() == 0) // use default
   constraints.gridy = r;
else
   constraints.gridx = Integer.parseInt(value);

A cell can contain any component, but we found it convenient to allow the user to specify more general Java beans. That lets us specify non-component types such as borders. A bean is defined by a class name and zero or more properties:

<!ELEMENT bean (class, property*)>
<!ELEMENT class (#PCDATA)>

As always when using beans, the class must have a default constructor.

A property contains a name and a value.

<!ELEMENT property (name, value)>
<!ELEMENT name (#PCDATA)>

The value is an integer, Boolean, string, or another bean:

<!ELEMENT value (int|string|boolean|bean)>
<!ELEMENT int (#PCDATA)>
<!ELEMENT string (#PCDATA)>
<!ELEMENT boolean (#PCDATA)>

Here is a typical example, a JLabel whose text property is set to the string "Face: ".

<bean>
  <class>javax.swing.JLabel</class>
  <property>
    <name>text</name>
    <value><string>Face: </string></value>
  </property>
</bean>

It seems like a bother to surround a string with the <string> tag. Why not just use #PCDATA for strings and leave the tags for the other types? Then we would need to use mixed content and weaken the rule for the value element to

<!ELEMENT value (#PCDATA|int|boolean|bean)*>

However, that rule would allow an arbitrary mixture of text and tags.

The program sets a property by using the BeanInfo class. The BeanInfo enumerates the property descriptors of the bean. We search for the property with the matching name, and then call its setter method with the supplied value.

When our program reads in a user interface description, it has enough information to construct and arrange the user interface components. But, of course, the interface is not alive—no event listeners have been attached. To add event listeners, it is necessary to locate the components. For that reason, we support an optional attribute of type ID for each bean:

<!ATTLIST bean id ID #IMPLIED>

For example, here is a combo box with an ID:

<bean id="face">
  <class>javax.swing.JComboBox</class>
</bean>

Recall that the parser checks that IDs are unique.

A programmer can attach event handlers like this:

gridbag = new GridBagPane("fontdialog.xml");
setContentPane(gridbag);
JComboBox face = (JComboBox)gridbag.get("face");
face.addListener(listener);

NOTE

graphics/note.gif
 

In this example, we only use XML to describe the component layout and leave it to programmers to attach the event handlers in the Java code. You could go a step further and add the code to the XML description. The most promising approach is to use a scripting language such as BeanShell (http://www.beanshell.org) for the code.

The program in Example 12-2 shows how to use the GridBagPane class to do all the boring work of setting up the grid bag layout. The layout is defined in Example 12-3. Figure 12-4 shows the result. The program only initializes the combo boxes (which are too complex for the bean property setting mechanism that the GridBagPane supports), and attaches event listeners. The GridBagPane class in Example 12-4 parses the XML file, constructs the components, and lays them out. Example 12-5 shows the DTD.

Figure 12-4. A font dialog defined by an XML layout

graphics/12fig04.gif
 

This example is a typical use of XML. The XML format is robust enough to express complex relationships. The XML parser adds real value by taking over the routine job of validity checking and supplying defaults. That reduces the effort for both the utility provider—the implementor of the GridBagPane class—and the user of this utility—the programmer who can now express user interface layouts in a file rather than lengthy code. Of course, authoring the XML file is still a bit tedious, even with an XML editor. The next step would be to provide a drag-and-drop authoring tool that automatically emits the XML code. With such an environment, the Java user interface programmer can enjoy the same productivity and convenience as a Windows or Mac programmer, while retaining the benefits of layout management.

NOTE

graphics/note.gif
 

The JSR-057 working group is proposing a more ambitious XML-based standard to describe and archive Java beans. See http://java.sun.com/products/jfc/tsc/articles/persistence/index.html for more information.

Example 12-2 GridBagTest.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import javax.swing.*;
 4.
 5. /**
 6.    This program shows how to use an XML file to describe
 7.    a gridbag layout
 8. */
 9. public class GridBagTest
10. {
11.    public static void main(String[] args)
12.    {
13.       JFrame frame = new FontFrame();
14.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15.       frame.show();
16.    }
17. }
18.
19. /**
20.    This frame contains a font selection dialog that
21.    is described by an XML file.
22. */
23. class FontFrame extends JFrame
24. {
25.    public FontFrame()
26.    {
27.       setSize(WIDTH, HEIGHT);
28.       setTitle("GridBagTest");
29.
30.       gridbag = new GridBagPane("fontdialog.xml");
31.       setContentPane(gridbag);
32.
33.       face = (JComboBox)gridbag.get("face");
34.       size = (JComboBox)gridbag.get("size");
35.       bold = (JCheckBox)gridbag.get("bold");
36.       italic = (JCheckBox)gridbag.get("italic");
37.
38.       face.setModel(new DefaultComboBoxModel(new Object[]
39.          {
40.             "Serif", "SansSerif", "Monospaced",
41.             "Dialog", "DialogInput"
42.          }));
43.
44.       size.setModel(new DefaultComboBoxModel(new Object[]
45.          {
46.             "8", "10", "12", "15", "18", "24", "36", "48"
47.          }));
48.
49.       ActionListener listener = new
50.          ActionListener()
51.          {
52.             public void actionPerformed(ActionEvent event)
53.             {
54.                setSample();
55.             }
56.          };
57.
58.       face.addActionListener(listener);
59.       size.addActionListener(listener);
60.       bold.addActionListener(listener);
61.       italic.addActionListener(listener);
62.
63.       setSample();
64.    }
65.
66.    /**
67.       This method sets the text sample to the selected font.
68.    */
69.    public void setSample()
70.    {
71.       String fontFace = (String)face.getSelectedItem();
72.       int fontSize = Integer.parseInt(
73.          (String)size.getSelectedItem());
74.       JTextArea sample = (JTextArea)gridbag.get("sample");
75.       int fontStyle
76.          = (bold.isSelected() ? Font.BOLD : 0)
77.          + (italic.isSelected() ? Font.ITALIC : 0);
78.
79.       sample.setFont(new Font(fontFace, fontStyle, fontSize));
80.       sample.repaint();
81.    }
82.
83.    private GridBagPane gridbag;
84.    private JComboBox face;
85.    private JComboBox size;
86.    private JCheckBox bold;
87.    private JCheckBox italic;
88.    private static final int WIDTH = 400;
89.    private static final int HEIGHT = 400;
90. }
Example 12-3 fontdialog.xml
 1. <?xml version="1.0"?>
 2. <!DOCTYPE gridbag SYSTEM "gridbag.dtd">
 3. <gridbag>
 4.   <row>
 5.     <cell anchor="EAST" weightx="0" weighty="0">
 6.       <bean>
 7.        <class>javax.swing.JLabel</class>
 8.        <property>
 9.          <name>text</name>
10.          <value><string>Face: </string></value>
11.        </property>
12.      </bean>
13.    </cell>
14.    <cell fill="HORIZONTAL" weighty="0">
15.      <bean id="face">
16.        <class>javax.swing.JComboBox</class>
17.      </bean>
18.    </cell>
19.    <cell gridheight="4" fill="BOTH">
20.      <bean id="sample">
21.        <class>javax.swing.JTextArea</class>
22.        <property>
23.          <name>text</name>
24.          <value><string>The quick brown fox jumps over the lazy
    dog</string></value>
25.        </property>
26.        <property>
27.          <name>editable</name>
28.          <value><boolean>false</boolean></value>
29.        </property>
30.        <property>
31.          <name>lineWrap</name>
32.          <value><boolean>true</boolean></value>
33.        </property>
34.        <property>
35.          <name>border</name>
36.          <value>
37.            <bean>
38.              <class>javax.swing.border.EtchedBorder</class>
39.            </bean>
40.          </value>
41.        </property>
42.      </bean>
43.    </cell>
44.  </row>
45.  <row>
46.    <cell anchor="EAST" weightx="0" weighty="0">
47.      <bean>
48.        <class>javax.swing.JLabel</class>
49.        <property>
50.          <name>text</name>
51.          <value><string>Size: </string></value>
52.        </property>
53.      </bean>
54.      </cell>
55.      <cell fill="HORIZONTAL" weighty="0">
56.        <bean id="size">
57.          <class>javax.swing.JComboBox</class>
58.        </bean>
59.      </cell>
60.    </row>
61.    <row>
62.      <cell gridwidth="2" weightx="0" fill="NONE">
63.        <bean id="bold">
64.          <class>javax.swing.JCheckBox</class>
65.          <property>
66.            <name>text</name>
67.            <value><string>Bold</string></value>
68.          </property>
69.        </bean>
70.      </cell>
71.    </row>
72.    <row>
73.      <cell gridwidth="2" weightx="0" fill="NONE">
74.        <bean id="italic">
75.         <class>javax.swing.JCheckBox</class>
76.         <property>
77.           <name>text</name>
78.           <value><string>Italic</string></value>
79.         </property>
80.       </bean>
81.     </cell>
82.   </row>
83. </gridbag>
Example 12-4 GridBagPane.java
  1. import java.awt.*;
  2. import java.beans.*;
  3. import java.io.*;
  4. import java.lang.reflect.*;
  5. import javax.swing.*;
  6. import javax.xml.parsers.*;
  7. import org.w3c.dom.*;
  8. import org.xml.sax.*;
  9.
 10. /**
 11.    This panel uses an XML file to describe its
 12.    components and their grid bag layout positions.
 13. */
 14. public class GridBagPane extends JPanel
 15. {
 16.    /**
 17.       Constructs a grid bag pane.
 18.       @param filename the name of the XML file that
 19.       describes the pane's components and their positions
 20.    */
 21.    public GridBagPane(String filename)
 22.    {
 23.       setLayout(new GridBagLayout());
 24.       constraints = new GridBagConstraints();
 25.
 26.       try
 27.       {
 28.          DocumentBuilderFactory factory
 29.             = DocumentBuilderFactory.newInstance();
 30.          factory.setValidating(true);
 31.          factory.setIgnoringElementContentWhitespace(true);
 32.          DocumentBuilder builder = factory.newDocumentBuilder();
 33.          Document doc = builder.parse(new File(filename));
 34.          parseGridbag(doc.getDocumentElement());
 35.       }
 36.       catch (ParserConfigurationException exception)
 37.       {
 38.          exception.printStackTrace();
 39.       }
 40.       catch (SAXException exception)
 41.       {
 42.          exception.printStackTrace();
 43.       }
 44.       catch (IOException exception)
 45.       {
 46.          exception.printStackTrace();
 47.       }
 48.    }
 49.
 50.    /**
 51.       Gets a component with a given name
 52.       @param name a component name
 53.       @return the component with the given name, or null if
 54.       no component in this grid bag pane has the given name
 55.    */
 56.    public Component get(String name)
 57.    {
 58.       Component[] components = getComponents();
 59.       for (int i = 0; i < components.length; i++)
 60.       {
 61.          if (components[i].getName().equals(name))
 62.             return components[i];
 63.       }
 64.       return null;
 65.    }
 66.
 67.    /**
 68.       Parses a gridbag element.
 69.       @param e a gridbag element
 70.    */
 71.    private void parseGridbag(Element e)
 72.    {
 73.       NodeList rows = e.getChildNodes();
 74.       for (int i = 0; i < rows.getLength(); i++)
 75.       {
 76.          Element row = (Element)rows.item(i);
 77.          NodeList cells = row.getChildNodes();
 78.          for (int j = 0; j < cells.getLength(); j++)
 79.          {
 80.             Element cell = (Element)cells.item(j);
 81.             parseCell(cell, i, j);
 82.          }
 83.       }
 84.    }
 85.
 86.    /**
 87.       Parses a cell element.
 88.       @param e a cell element
 89.       @param r the row of the cell
 90.       @param c the column of the cell
 91.    */
 92.    private void parseCell(Element e, int r, int c)
 93.    {
 94.       // get attributes
 95.
 96.       String value = e.getAttribute("gridx");
 97.       if (value.length() == 0) // use default
 98.       {
 99.          if (c == 0) constraints.gridx = 0;
100.          else constraints.gridx += constraints.gridwidth;
101.       }
102.       else
103.          constraints.gridx = Integer.parseInt(value);
104.
105.       value = e.getAttribute("gridy");
106.       if (value.length() == 0) // use default
107.          constraints.gridy = r;
108.       else
109.          constraints.gridx = Integer.parseInt(value);
110.
111.       constraints.gridwidth
112.          = Integer.parseInt(e.getAttribute("gridwidth"));
113.       constraints.gridheight
114.          = Integer.parseInt(e.getAttribute("gridheight"));
115.       constraints.weightx
116.          = Integer.parseInt(e.getAttribute("weightx"));
117.       constraints.weighty
118.          = Integer.parseInt(e.getAttribute("weighty"));
119.       constraints.ipadx
120.          = Integer.parseInt(e.getAttribute("ipadx"));
121.       constraints.ipady
122.          = Integer.parseInt(e.getAttribute("ipady"));
123.
124.       // use reflection to get integer values of static fields
125.       Class cl = GridBagConstraints.class;
126.
127.       try
128.       {
129.          String name = e.getAttribute("fill");
130.          Field f = cl.getField(name);
131.          constraints.fill = f.getInt(cl);
132.       }
133.       catch(Exception ex)
134.       {
135.       }
136.
137.       try
138.       {
139.          String name = e.getAttribute("anchor");
140.          Field f = cl.getField(name);
141.          constraints.anchor = f.getInt(cl);
142.       }
143.       catch(Exception ex)
144.       {
145.       }
146.
147.       Component comp = (Component)parseBean(
148.          (Element)e.getFirstChild());
149.       add(comp, constraints);
150.    }
151.
152.    /**
153.       Parses a bean element.
154.       @param e a bean element
155.    */
156.    private Object parseBean(Element e)
157.    {
158.       try
159.       {
160.          NodeList children = e.getChildNodes();
161.          Element classElement = (Element)children.item(0);
162.          String className
163.             = ((Text)classElement.getFirstChild()).getData();
164.
165.          Class cl = Class.forName(className);
166.
167.          Object obj = cl.newInstance();
168.
169.          if (obj instanceof Component)
170.             ((Component)obj).setName(e.getAttribute("id"));
171.
172.          for (int i = 1; i < children.getLength(); i++)
173.          {
174.          Node propertyElement = children.item(i);
175.          Element nameElement
176.             = (Element)propertyElement.getFirstChild();
177.          String propertyName
178.             = ((Text)nameElement.getFirstChild()).getData();
179.
180.          Element valueElement
181.             = (Element)propertyElement.getLastChild();
182.          Object value = parseValue(valueElement);
183.          BeanInfo beanInfo = Introspector.getBeanInfo(cl);
184.          PropertyDescriptor[] descriptors
185.             = beanInfo.getPropertyDescriptors();
186.          boolean done = false;
187.          for (int j = 0; !done && j < descriptors.length; j++)
188.          {
189.             if (descriptors[j].getName().equals(propertyName))
190.             {
191.                descriptors[j].getWriteMethod().invoke(obj,
192.                   new Object[] { value });
193.                done = true;
194.             }
195.          }
196.
197.       }
198.       return obj;
199.    }
200.    catch (Exception ex)
201.    {
202.      // the reflection methods can throw various exceptions
203.      ex.printStackTrace();
204.      return null;
205.    }
206.  }
207.
208.  /**
209.     Parses a value element.
210.     @param e a value element
211.  */
212.  private Object parseValue(Element e)
213.  {
214.     Element child = (Element)e.getFirstChild();
215.     if (child.getTagName().equals("bean"))
216.        return parseBean(child);
217.     String text = ((Text)child.getFirstChild()).getData();
218.     if (child.getTagName().equals("int"))
219.        return new Integer(text);
220.     else if (child.getTagName().equals("boolean"))
221.        return new Boolean(text);
222.     else if (child.getTagName().equals("string"))
223.        return text;
224.     else
225.        return null;
226.     }
227.
228.     private GridBagConstraints constraints;
229. }
Example 12-5 gridbag.dtd
 1. <!ELEMENT gridbag (row)*>
 2. <!ELEMENT row (cell)*>
 3. <!ELEMENT cell (bean)>
 4. <!ATTLIST cell gridx CDATA #IMPLIED>
 5. <!ATTLIST cell gridy CDATA #IMPLIED>
 6. <!ATTLIST cell gridwidth CDATA "1">
 7. <!ATTLIST cell gridheight CDATA "1">
 8. <!ATTLIST cell weightx CDATA "100">
 9. <!ATTLIST cell weighty CDATA "100">
10. <!ATTLIST cell fill (NONE|BOTH|HORIZONTAL|VERTICAL) "NONE">
11. <!ATTLIST cell anchor (CENTER|NORTH|NORTHEAST|EAST|SOUTH
    EAST|SOUTH|SOUTHWEST|WEST|NORTHWEST) "CENTER">
12. <!ATTLIST cell ipadx CDATA "0">
13. <!ATTLIST cell ipady CDATA "0">
14.
15. <!ELEMENT bean (class, property*)>
16. <!ATTLIST bean id ID #IMPLIED>
17. <!ELEMENT class (#PCDATA)>
18. <!ELEMENT property (name, value)>
19. <!ELEMENT name (#PCDATA)>
20. <!ELEMENT value (int|string|boolean|bean)>
21. <!ELEMENT int (#PCDATA)>
22. <!ELEMENT string (#PCDATA)>
23. <!ELEMENT boolean (#PCDATA)>

Namespaces

Java uses packages to avoid name clashes. Programmers can use the same name for different classes as long as they aren't in the same package. XML has a similar namespace mechanism for element and attribute names.

A namespace is identified by a Uniform Resource Identifier (URI), such as

http://www.w3.org/2001/XMLSchema
uuid:1c759aed-b748-475c-ab68-10679700c4f2
urn:com:books-r-us

The HTTP URL form is the most common. Note that the URL is just used as an identifier string, not to locate a document. For example, the namespace identifiers

http://www.horstmann.com/corejava

http://www.horstmann.com/corejava/index.html

denote different namespaces, even though a web server would serve the same document for both URLs.

There doesn't have to be any document at a namespace URL—the XML parser doesn't attempt to find anything at that location. However, as a help to programmers who encounter a possibly unfamiliar namespace, it is customary to place a document explaining the purpose of the namespace at the URL location. For example, if you point your browser to the namespace URL for the XML Schema namespace (http://www.w3.org/2001/XMLSchema), you will find a document describing the XML Schema standard.

Why use HTTP URLs for namespace identifiers? It is easy to ensure that they are unique. If you choose a real URL, then the host part's uniqueness is guaranteed by the domain name system. Your organization can then arrange for the uniqueness of the remainder of the URL. This is the same rationale that underlies the use of reversed domain names in Java package names.

Of course, while you want long namespace identifiers for uniqueness, you don't want to deal with long identifiers any more than you have to. In Java, you use the import mechanism to specify the long names of packages, and then use just the short class names. In XML, there is a similar mechanism, like this:

<element xmlns="namespace URI">
   children
</element>

The element and its children are now part of the given namespace.

A child can provide its own namespace, for example:

 <element xmlns="namespace URI">
   <child xmlns="namespace URI #2">
      grandchildren
   </child>
   more children
</element>

Then the first child and the grandchildren are part of the second namespace.

That simple mechanism works well if you only need a single namespace, or if the namespaces are naturally nested. Otherwise, you will want to use a second mechanism that has no analog in Java. You can have an alias for a namespace—a short identifier that you choose for a particular document. Here is a typical example:

<xsl:stylesheet
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html"/>
   . . .
</xsl:stylesheet>

The attribute

xmlns:alias="namespace URI"

defines a namespace and an alias. In our example, the alias is the string xsl. Thus, xsl:stylesheet really means "stylesheet in the namespace http://www.w3.org/1999/XSL/Transform".

NOTE

graphics/note.gif
 

Only child elements inherit the namespace of their parent. Attributes without an explicit alias prefix are never part of a namespace. Consider this contrived example:

<configuration xmlns="http://www.horstmann.com/corejava"
   xmlns:si="http://www.bipm.fr/enus/3_SI/si.html"
>
   <size value="210" si:unit="mm"/>
   . . .
</configuration>

The elements configuration and size are part of the namespace with URI http://www.horstmann.com/corejava. The attribute si:unit is part of the namespace with URI http://www.bipm.fr/enus/3_SI/si.html. But the attribute value is not part of any namespace.

You can control how the parser deals with namespaces. By default, the Sun DOM parser is not "namespace aware."

To turn on namespace handling, call the setNamespaceAware method of the DocumentBuilderFactory:

factory.setNamespaceAware(true);

Then all builders that the factory produces support namespaces. Each node has three properties:

Here is an example. Suppose the parser sees the following element:

<xsl:stylesheet
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

Then it reports the following:

NOTE

graphics/note.gif
 

If namespace awareness is turned off, then getLocalName and getNamespaceURI return null.

org.w3c.dom.Node

graphics/api.gif
 

javax.xml.parsers.DocumentBuilderFactory

graphics/api.gif
 

Using the SAX Parser

The DOM parser reads an XML document in its entirety into a tree data structure. For most practical applications, DOM works fine. But it can be inefficient if the document is large and if your processing algorithm is simple enough that you can analyze nodes "on the fly," without having to see all of the tree structure. In these cases, you want to use the SAX parser instead. The SAX parser reports events as it parses the components of the XML input. But it does not store the document in any way—it is up to the event handlers whether they want to build a data structure. In fact, the DOM parser is built on top of the SAX parser. It builds the DOM tree as it receives the parser events.

Whenever you use a SAX parser, you need a handler that defines the event actions for the various parse events. The ContentHandler interface defines several callback methods that the parser executes as it parses the document. Here are the most important ones:

For example, when parsing the fragment

<font>
   <name>Helvetica</name>
   <size units="pt">36</size>
</font>

the parser makes sure the following calls are generated:

  1. startElement, element name: font

  2. startElement, element name: name

  3. characters, content: Helvetica

  4. endElement, element name: name

  5. startElement, element name: size, attributes: units="pt"

  6. characters, content: 36

  7. endElement, element name: size

  8. endElement, element name: font

Your handler needs to override these methods and have them carry out whatever action you want to carry out as you parse the file. The program at the end of this section prints out all links <a href="..."> in an HTML file. It simply overrides the startElement method of the handler to check for links with name a and an attribute with name href. This is potentially useful for implementing a "web crawler," a program that reaches more and more web pages by following links.

NOTE

graphics/note.gif
 

Unfortunately, most HTML pages deviate so much from proper XML that the example program will not be able to parse them. As already mentioned, the World Wide Web Consortium (W3C) recommends that web designers use XHTML, an HTML dialect that can be displayed by current web browsers and that is also proper XML. See http://www.w3.org/TR/xhtml1/ for more information on XHTML. Since the W3C "eats its own dog food," their web pages are written in XHTML. You can use those pages to test the example program. For example, if you run

java SAXTest http://www.w3c.org/MarkUp

then you will see a list of the URLs of all links on that page.

The sample program is a good example for the use of SAX. We don't care at all in which context the a elements occur, and there is no need to store a tree structure.

Here is how you get a SAX parser:

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();

You can now process a document:

parser.parse(source, handler);

Here, source can be a file, URL string, or input stream. The handler belongs to a subclass of DefaultHandler. The DefaultHandler class defines do-nothing methods for the four interfaces:

ContentHandler
DTDHandler
EntityResolver
ErrorHandler

The example program defines a handler that overrides the startElement method of the ContentHandler interface to watch out for a elements with an href attribute:

DefaultHandler handler = new
   DefaultHandler()
   {
      public void startElement(String namespaceURI,
         String lname, String qname, Attributes attrs)
      throws SAXException
      {
         if (lname.equalsIgnoreCase("a") && attrs != null)
         {
            for (int i = 0; i < attrs.getLength(); i++)
            {
               String aname = attrs.getLocalName(i);
               if (aname.equalsIgnoreCase("href"))
                  System.out.println(attrs.getValue(i));
            }
         }
      }
   };

The startElement method has three parameters that describe the element name. The qname parameter reports the qualified name of the form alias:localname. If namespace processing is turned on, then the namespaceURI and lname parameters describe the namespace and local (unqualified) name.

As with the DOM parser, namespace processing is turned off by default. You activate namespace processing by calling the setNamespaceAware method of the factory class:

SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();

Example 12-6 contains the code for the web crawler program. Later in this chapter, you will see another interesting use of SAX. An easy way of turning a non-XML data source into XML is to report the SAX events that an XML parser would report. See the section on XSL transformations for details.

Example 12-6 SAXTest.java
 1. import java.io.*;
 2. import java.net.*;
 3. import javax.xml.parsers.*;
 4. import org.xml.sax.*;
 5. import org.xml.sax.helpers.*;
 6.
 7. /**
 8.    This program demonstrates how to use a SAX parser. The
 9.    program prints all hyperlinks links of an XHTML web page.
10.    Usage: java SAXTest url
11. */
12. public class SAXTest
13. {
14.    public static void main(String[] args) throws Exception
15.    {
16.       String url;
17.       if (args.length == 0)
18.       {
19.          url = "http://www.w3c.org";
20.          System.out.println("Using " + url);
21.       }
22.       else
23.          url = args[0];
24.
25.       DefaultHandler handler = new
26.          DefaultHandler()
27.          {
28.             public void startElement(String namespaceURI,
29.                String lname, String qname, Attributes attrs)
30.             {
31.                if (lname.equalsIgnoreCase("a") && attrs != null)
32.                {
33.                   for (int i = 0; i < attrs.getLength(); i++)
34.                   {
35.                      String aname = attrs.getLocalName(i);
36.                      if (aname.equalsIgnoreCase("href"))
37.                         System.out.println(attrs.getValue(i));
38.                   }
39.                }
40.             }
41.          };
42.
43.       SAXParserFactory factory = SAXParserFactory.newInstance();
44.       factory.setNamespaceAware(true);
45.       SAXParser saxParser = factory.newSAXParser();
46.       InputStream in = new URL(url).openStream();
47.       saxParser.parse(in, handler);
48.    }
49.}

javax.xml.parsers.SAXParserFactory

graphics/api.gif
 

javax.xml.parsers.SAXParser

graphics/api.gif
 

org.xml.sax.ContentHandler

graphics/api.gif
 

org.xml.sax.Attributes

graphics/api.gif
 

Generating XML Documents

You now know how to write Java programs that read XML. Let us now turn to the opposite process, producing XML output. Of course, you could write an XML file simply by making a sequence of print calls, printing the elements, attributes, and text content. But that would not be a good idea. The code is rather tedious, and you can easily make mistakes if you don't pay attention to special symbols (such as " or <) in the attribute values and text content.

A better approach is to build up a DOM tree with the contents of the document, and then write out the tree contents. To build a DOM tree, you start out with an empty document. You can get an empty document by calling the newDocument method of the DocumentBuilder class.

Document doc = builder.newDocument();

Use the createElement method of the Document class to construct the elements of your document.

Element rootElement = doc.createElement(rootName);
Element childElement = doc.createElement(childName);

Use the createTextNode method to construct text nodes:

Text textNode = doc.createTextNode(textContents);

Add the root element to the document, and add the child nodes to their parents:

doc.appendChild(rootElement);
rootElement.appendChild(childElement);
childElement.appendChild(textNode);

As you build up the DOM tree, you may also need to set element attributes. Simply call the setAttribute method of the Element class:

rootElement.setAttribute(name, value);

Somewhat curiously, the DOM API currently has no support for writing a DOM tree to an output stream. To overcome this limitation, we will use the XML Style Sheet Transformations (XSLT) API. We will apply the "do nothing" transformation to the document and capture its output. To include a DOCTYPE node in the output, you also need to set the SYSTEM and PUBLIC identifiers as output properties.

// construct the "do nothing" transformation

Transformer t = TransformerFactory
   .newInstance().newTransformer();
// set output properties to get a DOCTYPE node
t.setOutputProperty("doctype-system", systemIdentifier);
t.setOutputProperty("doctype-public", publicIdentifier);
// apply the "do nothing" transformation
// and send the output to a file
t.transform(new DOMSource(doc),
   new StreamResult(new FileOutputStream(file)));

For more information about XSLT, turn to the next section. Right now, consider this code a "magic incantation" to produce XML output.

NOTE

graphics/note.gif
 

The resulting XML file contains no whitespace (that is, no line breaks or indentations). If you like whitespace, set the "indent" output property to "yes".

Example 12-7 is a typical program that produces XML output. The program draws a modernist painting—a random set of colored rectangles (see Figure 12-5). To save a masterpiece, we use the Scalable Vector Graphics (SVG) format. SVG is an XML format to describe complex graphics in a device-independent fashion. You can find more information about SVG at http://www.w3c.org/Graphics/SVG. To view SVG files, download the Apache Batik viewer (http://xml.apache.org/batik) or the Adobe browser plug-in (http://www.adobe.com/svg/main.html). Figure 12-6 shows the Apache Batik viewer.

Figure 12-5. Generating Modern Art

graphics/12fig05.gif
 

Figure 12-6. The Apache Batik SVG Viewer

graphics/12fig06.gif
 

We don't want to go into details about SVG. If you are interested in SVG, we suggest you start with the tutorial on the Adobe site. For our purposes, we just need to know how to express a set of colored rectangles. Here is a sample:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000802//EN"
"http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd">
<svg width="300" height="150">
<rect x="231" y="61" width="9" height="12" fill="#6e4a13"/>
<rect x="107" y="106" width="56" height="5" fill="#c406be"/>
. . .
</svg>

As you can see, each rectangle is described as a rect node. The position, width, height, and fill color are attributes. The fill color is an RGB value in hexadecimal.

NOTE

graphics/note.gif
 

As you can see, SVG uses attributes heavily. In fact, some attributes are quite complex. For example, here is a path element:

<path d="M 100 100 L 300 100 L 200 300 z">

The M denotes a "moveto" command, L is "lineto," and z is "closepath" (!). Apparently, the designers of this data format didn't have much confidence in using XML for structured data. In your own XML formats, you may want to use elements instead of complex attributes.

Here is the source code for the program. You can use the same technique whenever you need to generate XML output.

Example 12-7 XMLWriteTest.java
  1.import java.awt.*;
  2.import java.awt.geom.*;
  3.import java.io.*;
  4.import java.util.*;
  5.import java.awt.event.*;
  6.import javax.swing.*;
  7.import javax.xml.parsers.*;
  8.import javax.xml.transform.*;
  9.import javax.xml.transform.dom.*;
 10.import javax.xml.transform.stream.*;
 11.import org.w3c.dom.*;
 12.
 13.
 14. /**
 15.    This program shows how to write an XML file. It saves
 16.    a file describing a modern drawing in SVG format.
 17. */
 18. public class XMLWriteTest
 19. {
 20.    public static void main(String[] args)
 21.    {
 22.       XMLWriteFrame frame = new XMLWriteFrame();
 23.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 24.       frame.show();
 25.    }
 26. }
 27.
 28. /**
 29.    A frame with a panel for showing a modern drawing.
 30. */
 31. class XMLWriteFrame extends JFrame
 32. {
 33.    public XMLWriteFrame()
 34.    {
 35.       setTitle("XMLWriteTest");
 36.       setSize(WIDTH, HEIGHT);
 37.
 38.       // add panel to frame
 39.
 40.       panel = new RectanglePanel();
 41.       Container contentPane = getContentPane();
 42.       contentPane.add(panel);
 43.
 44.       // set up menu bar
 45.
 46.       JMenuBar menuBar = new JMenuBar();
 47.       setJMenuBar(menuBar);
 48.
 49.       JMenu menu = new JMenu("File");
 50.       menuBar.add(menu);
 51.
 52.       JMenuItem newItem = new JMenuItem("New");
 53.       menu.add(newItem);
 54.       newItem.addActionListener(new
 55.          ActionListener()
 56.          {
 57.             public void actionPerformed(ActionEvent event)
 58.             {
 59.                panel.newDrawing();
 60.             }
 61.          });
 62.
 63.       JMenuItem saveItem = new JMenuItem("Save");
 64.       menu.add(saveItem);
 65.       saveItem.addActionListener(new
 66.          ActionListener()
 67.          {
 68.             public void actionPerformed(ActionEvent event)
 69.             {
 70.                try
 71.                {
 72.                   saveDocument();
 73.                }
 74.                catch (TransformerException exception)
 75.                {
 76.                   JOptionPane.showMessageDialog(
 77.                      XMLWriteFrame.this, exception.toString());
 78.                }
 79.                catch (IOException exception)
 80.                {
 81.                   JOptionPane.showMessageDialog(
 82.                      XMLWriteFrame.this, exception.toString());
 83.                }
 84.             }
 85.          });
 86.
 87.       JMenuItem exitItem = new JMenuItem("Exit");
 88.       menu.add(exitItem);
 89.       exitItem.addActionListener(new
 90.          ActionListener()
 91.          {
 92.             public void actionPerformed(ActionEvent event)
 93.             {
 94.                System.exit(0);
 95.             }
 96.          });
 97.
 98.    }
 99.
100.    /**
101.       Saves the drawing in SVG format.
102.    */
103.    public void saveDocument()
104.       throws TransformerException, IOException
105.    {
106.       JFileChooser chooser = new JFileChooser();
107.      if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
108.          return;
109.       File f = chooser.getSelectedFile();
110.       Document doc = panel.buildDocument();
111.       Transformer t = TransformerFactory
112.          .newInstance().newTransformer();
113.
114.       t.setOutputProperty("doctype-system",
115. "http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd"
116.          );
117.       t.setOutputProperty("doctype-public",
118.          "-//W3C//DTD SVG 20000802//EN");
119.
120.       t.transform(new DOMSource(doc),
121.          new StreamResult(new FileOutputStream(f)));
122.    }
123.
124.    public static final int WIDTH = 300;
125.    public static final int HEIGHT = 200;
126.
127.    private RectanglePanel panel;
128.}
129.
130./**
131.    A panel that shows a set of colored rectangles
132.*/
133.class RectanglePanel extends JPanel
134.{
135.    public RectanglePanel()
136.    {
137.       rects = new ArrayList();
138.       colors = new ArrayList();
139.       generator = new Random();
140.
141.       DocumentBuilderFactory factory
142.          = DocumentBuilderFactory.newInstance();
143.       try
144.       {
145.          builder = factory.newDocumentBuilder();
146.       }
147.       catch (ParserConfigurationException exception)
148.       {
149.          exception.printStackTrace();
150.       }
151.    }
152.
153.    /**
154.       Create a new random drawing.
155.    */
156.    public void newDrawing()
157.    {
158.       int n = 10 + generator.nextInt(20);
159.       rects.clear();
160.       for (int i = 1; i <= n; i++)
161.       {
162.          int x = generator.nextInt(getWidth());
163.          int y = generator.nextInt(getHeight());
164.          int width = generator.nextInt(getWidth() - x);
165.          int height = generator.nextInt(getHeight() - y);
166.          rects.add(new Rectangle(x, y, width, height));
167.          int r = generator.nextInt(256);
168.          int g = generator.nextInt(256);
169.          int b = generator.nextInt(256);
170.          colors.add(new Color(r, g, b));
171.       }
172.       repaint();
173.    }
174.
175.    public void paintComponent(Graphics g)
176.    {
177.       if (rects.size() == 0) newDrawing();
178.       super.paintComponent(g);
179.       Graphics2D g2 = (Graphics2D)g;
180.
181.       // draw all rectangles
182.       for (int i = 0; i < rects.size(); i++)
183.       {
184.          g2.setColor((Color)colors.get(i));
185.          g2.fill((Rectangle2D)rects.get(i));
186.       }
187.    }
188.
189.    /**
190.       Creates an SVG document of the current drawing.
191.       @return the DOM tree of the SVG document
192.    */
193.    public Document buildDocument()
194.    {
195.
196.       Document doc = builder.newDocument();
197.       Element svgElement = doc.createElement("svg");
198.       doc.appendChild(svgElement);
199.       svgElement.setAttribute("width", "" + getWidth());
200.       svgElement.setAttribute("height", "" + getHeight());
201.
202.       for (int i = 0; i < rects.size(); i++)
203.       {
204.          Color c = (Color)colors.get(i);
205.          Rectangle2D r = (Rectangle2D)rects.get(i);
206.          Element rectElement = doc.createElement("rect");
207.          rectElement.setAttribute("x", "" + r.getX());
208.          rectElement.setAttribute("y", "" + r.getY());
209.          rectElement.setAttribute("width", "" + r.getWidth());
210.          rectElement.setAttribute("height", "" + r.getHeight());
211.          rectElement.setAttribute("fill", colorToString(c));
212.          svgElement.appendChild(rectElement);
213.       }
214.
215.       return doc;
216.    }
217.
218.    /**
219.       Converts a color to a hex value.
220.       @param c a color
221.       @return a string of the form #rrggbb
222.    */
223.    private static String colorToString(Color c)
224.    {
225.       StringBuffer buffer = new StringBuffer();
226.       buffer.append(Integer.toHexString(
227.          c.getRGB() & 0xFFFFFF));
228.       while(buffer.length() < 6) buffer.insert(0, '0');
229.       buffer.insert(0, '#');
230.       return buffer.toString();
231.    }
232.
233.    private ArrayList rects;
234.    private ArrayList colors;
235.    private Random generator;
236.    private DocumentBuilder builder;
237. }

javax.xml.parsers.DocumentBuilder

graphics/api.gif
 

org.w3c.dom.Document

graphics/api.gif
 

org.w3c.dom.Node

graphics/api.gif
 

org.w3c.dom.Element

graphics/api.gif
 

javax.xml.transform.TransformerFactory

graphics/api.gif
 

javax.xml.transform.Transformer

graphics/api.gif
 

javax.xml.transform.dom.DOMSource

graphics/api.gif
 

javax.xml.transform.stream.StreamResult

graphics/api.gif
 

XSL Transformations

As you have seen, the XML format is a very useful interchange format for structured data. However, most XML data is not intended for viewing by end-users. In this section, you will see how to transform XML data into presentation formats such as HTML or plain text.

NOTE

graphics/note.gif
 

In this section, you will see how to transform XML data into HTML for presentation in a browser. An alternate approach is to display XML files directly in a browser. For example, Internet Explorer shows XML documents as trees. More importantly, the latest versions of Netscape, Internet Explorer, and Opera let you specify a cascading style sheet (CSS) with an XML document. With a style sheet, you can control how you want the browser to display the contents of XML elements. You can find the style sheet specification at http://www.w3c.org/TR/REC-CSS2. The article "XML and CSS: Structured Markup with Display Semantics" by Pankaj Kamthan (http://tech.irt.org/articles/js198) contains a nice discussion of the pros and cons of using CSS with XML.

The purpose of a style sheet with transformation templates is to describe the conversion of XML documents into some other format (see Figure 12-7).

Figure 12-7. Applying XSL Transformations

graphics/12fig07.gif
 

Here is a typical example. We want to transform XML files with employee records into HTML documents. Consider this input file.

<staff>
   <employee>
      <name>Carl Cracker</name>
      <salary>75000</salary>
      <hiredate year="1987" month="12" day="15"/>
   </employee>
   <employee>
      <name>Harry Hacker</name>
      <salary>50000</salary>
      <hiredate year="1989" month="10" day="1"/>
   </employee>
   <employee>
      <name>Tony Tester</name>
      <salary>40000</salary>
      <hiredate year="1990" month="3" day="15"/>
   </employee>
</staff>

The desired output is an HTML table:

<table border="1">
<tr>
<td>Carl Cracker</td><td>$75000.0</td><td>1987-12-15</td>
</tr>
<tr>
<td>Harry Hacker</td><td>$50000.0</td><td>1989-10-1</td>
</tr>
<tr>
<td>Tony Tester</td><td>$40000.0</td><td>1990-3-15</td>
</tr>
</table>

This table can be included in a larger HTML document, for example a Java Server Page.

The XSLT specification is quite complex, and entire books have been written on the subject. We can't possibly discuss all the features of XSLT, so we will only work through a representative example. You can find more information in the book Essential XML by Don Box, et al. The XSL specification is available at http://www.w3.org/TR/xslt.

A style sheet with transformation templates has this form:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   version="1.0">
   <xsl:output method="html"/>
   . . .
   templates
   . . .
</xsl:stylesheet>

In our example, the xsl:output element specifies the method as HTML. Other valid method settings are xml and text.

Here is a typical template:

<xsl:template match="/staff/employee">
   <tr><xsl:apply-templates/></tr>
</xsl:template>

The value of the match attribute is an XPath expression. XPath is yet another XML standard. An XPath describes a set of nodes in an XML document. For example, the XPath

/staff/employee

describes all employee elements that are children of the staff root element.

The XPath

/staff/employee/hiredate/@year

describes all year attribute nodes of hiredate elements within employee elements that are children of the staff root node. The @ sign denotes an attribute.

The XPath

/staff/employee/name/text()

describes all text nodes that are children of name elements within employee elements that are children of the staff root node. The () denote a function—besides text(), there are a number of other functions that can be used inside XPath expressions.

There are many more elaborate XPath expressions—see Essential XML by Don Box or the specification at http://www.w3c.org/TR/xpath.

Let us now return to the example template. It states: Whenever you see a node in the XPath set /staff/employee, do the following:

In other words, this template generates the HTML table row markers around every employee record.

The XSLT processor starts processing by examining the root element. Whenever a node matches one of the templates, then it applies the template. (If multiple templates match, the best-matching one is used—see the specification for the gory details.) If no template matches, the processor carries out a default action. For text nodes, the default is to include the contents in the output. For elements, the default action is to create no output but to keep processing the children.

Here is a template for transforming name nodes in an employee file:

<xsl:template match="/staff/employee/name">
   <td><xsl:apply-templates/></td>
</xsl:template>

As you can see, the template produces the <td>...</td> delimiters, and it asks the processor to recursively visit the children of the name element. There is just one child, the text node. When the processor visits that node, it emits the text contents (provided, of course, that there is no other matching template).

You have to work a little harder if you want to copy attribute values into the output. Here is an example:

<xsl:template match="/staff/employee/hiredate">
   <td><xsl:value-of select="@year"/>-<xsl:value-of
   select="@month"/>-<xsl:value-of select="@day"/></td>
</xsl:template>

When processing a hiredate node, this template emits

The xsl:value-of statement computes the string value of a node set. The node set is specified by the XPath value of the select attribute. In this case, the path is relative to the currently processed node. The node set is converted to a string by concatenating the string values of all nodes. The string value of an attribute node is its value. The string value of a text node is its contents. The string value of an element node is the concatenation of the string values of its child nodes (but not its attributes).

Example 12-9 contains all transformation templates to turn an XML file with employee records into an XML table.

Example 12-10 shows a different set of transformations. The input is the same XML file, and the output is plain text in the familiar property file format:

employee.1.name=Carl Cracker
employee.1.salary=75000.0
employee.1.hiredate=1987-12-15
employee.2.name=Harry Hacker
employee.2.salary=50000.0
employee.2.hiredate=1989-10-1
employee.3.name=Tony Tester
employee.3.salary=40000.0
employee.3.hiredate=1990-3-15

That example uses the position() function which yields the position of the current node, as seen from its parent. We get an entirely different output, simply by switching the style sheet. Thus, you can safely use XML to describe your data, even if some applications need the data in another format. Just use XSLT to generate the alternative format.

It is extremely simple to generate XSL transformations in Java. Set up a transformer factory for each style sheet. Then get a transformer object, and tell it to transform a source to a result.

File styleSheet = new File(filename);
StreamSource styleSource = new StreamSource(styleSheet);
Transformer t = TransformerFactory
   .newInstance().newTransformer(styleSource);
t.transform(source, result);

The parameters of the transform method are objects of classes that implement the Source and Result interfaces. There are three implementations of the Source interface:

DOMSource
SAXSource
StreamSource

You can construct a StreamSource from a file, stream, reader, or URL, and a DOMSource from the node of a DOM tree. For example, in the preceding section, we invoked the identity transformation as

t.transform(new DOMSource(doc), result);

In our example program, we will do something slightly more interesting. Rather than starting out with an existing XML file, we will produce a SAX XML reader that gives the illusion of parsing an XML file, by emitting appropriate SAX events. Actually, the XML reader reads a flat file, as described in Chapter 12 of Volume 1. The input file looks like this:

Carl Cracker|75000.0|1987|12|15
Harry Hacker|50000.0|1989|10|1
Tony Tester|40000.0|1990|3|15

The XML reader generates SAX events as it processes the input. Here is a part of the parse method of the EmployeeReader class that implements the XMLReader interface.

AttributesImpl attributes = new AttributesImpl();
handler.startDocument();
handler.startElement("", "staff", "staff", attributes);
while ((line = in.readLine()) != null)
{
   handler.startElement("", "employee", "employee", attributes);
   StringTokenizer t = new StringTokenizer(line, "|");
   handler.startElement("", "name", "name", attributes);
   String s = t.nextToken();
   handler.characters(s.toCharArray(), 0, s.length());
   handler.endElement("", "name", "name");
   . . .
   handler.endElement("", "employee", "employee");
}
handler.endElement("", rootElement, rootElement);
handler.endDocument();

The SAXSource for the transformer is constructed from the XML reader:

t.transform(new SAXSource(new EmployeeReader(),
   new InputSource(new FileInputStream(filename))), result);

This is an ingenious trick to convert non-XML legacy data into XML. Of course, most XSLT applications will already have XML input data, and you can simply invoke the transform method on a StreamSource, like this:

t.transform(new StreamSource(file), result);

The transformation result is an object of a class that implements the Result interface. The Java library supplies three classes:

DOMResult
SAXResult
StreamResult

To store the result in a DOM tree, use a DocumentBuilder to generate a new document node and wrap it into a DOMResult:

Document doc = builder.newDocument();
t.transform(source, new DOMResult(doc));

To save the output in a file, use a StreamResult:

t.transform(source, new StreamResult(file));

Example 12-8 contains the complete source code. Examples 12-9 and 12-10 contain two style sheets. This example concludes our discussion of the XML support in the Java library. We hope you now have a good perspective of the major strengths of XML, in particular automated parsing and validation, and a powerful transformation mechanism. Of course, all this technology is only going to work for you if you design your XML formats well. You need to make sure that the formats are rich enough to express all your business needs, that they are stable over time, and that your business partners are willing to accept your XML documents. Those issues can be far more challenging than dealing with parsers, DTDs or transformations.

Example 12-8 TransformTest.java
  1. import java.io.*;
  2. import java.util.*;
  3. import javax.xml.parsers.*;
  4. import javax.xml.transform.*;
  5. import javax.xml.transform.dom.*;
  6. import javax.xml.transform.sax.*;
  7. import javax.xml.transform.stream.*;
  8. import org.xml.sax.*;
  9. import org.xml.sax.helpers.*;
 10.
 11. /**
 12.    This program demonstrates XSL transformations. It applies
 13.    a transformation to a set of employee records. The records
 14.    are stored in the file employee.dat and turned into XML
 15.    format. Specify the stylesheet on the command line, e.g.
 16.    java TransformTest makeprop.xsl
 17. */
 18. public class TransformTest
 19. {
 20.    public static void main(String[] args) throws Exception
 21.    {
 22.       String filename;
 23.       if (args.length > 0) filename = args[0];
 24.       else filename = "makehtml.xsl";
 25.       File styleSheet = new File(filename);
 26.       StreamSource styleSource = new StreamSource(styleSheet);
 27.
 28.       Transformer t = TransformerFactory
 29.          .newInstance().newTransformer(styleSource);
 30.       t.transform(new SAXSource(new EmployeeReader(),
 31.          new InputSource(new FileInputStream("employee.dat"))),
 32.          new StreamResult(System.out));
 33.    }
 34. }
 35.
 36. /**
 37.    This class reads the flat file employee.dat and reports SAX
 38.    parser events to act as if it was parsing an XML file.
 39. */
 40. class EmployeeReader implements XMLReader
 41. {
 42.    public void parse(InputSource source)
 43.       throws IOException, SAXException
 44.    {
 45.       InputStream stream = source.getByteStream();1
 46.       BufferedReader in = new BufferedReader(
 47.          new InputStreamReader(stream));
 48.       String rootElement = "staff";
 49.       AttributesImpl atts = new AttributesImpl();
 50.
 51.       if (handler == null)
 52.          throw new SAXException("No content handler");
 53.
 54.       handler.startDocument();
 55.    handler.startElement("", rootElement, rootElement, atts);
 56.       String line;
 57.       while ((line = in.readLine()) != null)
 58.       {
 59.       handler.startElement("", "employee", "employee", atts);
 60.          StringTokenizer t = new StringTokenizer(line, "|");
 61.
 62.          handler.startElement("", "name", "name", atts);
 63.          String s = t.nextToken();
 64.          handler.characters(s.toCharArray(), 0, s.length());
 65.          handler.endElement("", "name", "name");
 66.
 67.          handler.startElement("", "salary", "salary", atts);
 68.          s = t.nextToken();
 69.          handler.characters(s.toCharArray(), 0, s.length());
 70.          handler.endElement("", "salary", "salary");
 71.
 72.          atts.addAttribute("", "year", "year", "CDATA",
 73.             t.nextToken());
 74.          atts.addAttribute("", "month", "month", "CDATA",
 75.             t.nextToken());
 76.          atts.addAttribute("", "day", "day", "CDATA",
 77.             t.nextToken());
 78.          handler.startElement("", "hiredate", "hiredate", atts);
 79.          handler.endElement("", "hiredate", "hiredate");
 80.          atts.clear();
 81.
 82.          handler.endElement("", "employee", "employee");
 83.       }
 84.
 85.       handler.endElement("", rootElement, rootElement);
 86.       handler.endDocument();
 87.    }
 88.
 89.    public void setContentHandler(ContentHandler aHandler)
 90.    {
 91.       handler = aHandler;
 92.    }
 93.
 94.    public ContentHandler getContentHandler()
 95.    {
 96.       return handler;
 97.    }
 98.
 99.    // the following methods are just do-nothing implementations
100.    public void parse(String systemId)
101.       throws IOException, SAXException {}
102.    public void setErrorHandler(ErrorHandler handler) {}
103.    public ErrorHandler getErrorHandler() { return null; }
104.    public void setDTDHandler(DTDHandler handler) {}
105.    public DTDHandler getDTDHandler() { return null; }
106.    public void setEntityResolver(EntityResolver resolver) {}
107.    public EntityResolver getEntityResolver() { return null; }
108.    public void setProperty(String name, Object value) {}
109.    public Object getProperty(String name) { return null; }
110.    public void setFeature(String name, boolean value) {}
111.    public boolean getFeature(String name) { return false; }
112.
113.    private ContentHandler handler;
114. }
Example 12-9 makehtml.xsl
 1. <?xml version="1.0" encoding="ISO-8859-1"?>
 2.
 3. <xsl:stylesheet
 4.    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 5.    version="1.0">
 6.
 7.    <xsl:output method="html"/>
 8.
 9.    <xsl:template match="/staff">
10.       <table border="1"><xsl:apply-templates/></table>
11.    </xsl:template>
12.
13.    <xsl:template match="/staff/employee">
14.       <tr><xsl:apply-templates/></tr>
15.    </xsl:template>
16.
17.    <xsl:template match="/staff/employee/name">
18.       <td><xsl:apply-templates/></td>
19.    </xsl:template>
20.
21.    <xsl:template match="/staff/employee/salary">
22.       <td>$<xsl:apply-templates/></td>
23.    </xsl:template>
24.
25.    <xsl:template match="/staff/employee/hiredate">
26.       <td><xsl:value-of select="@year"/>-<xsl:value-of
27.       select="@month"/>-<xsl:value-of select="@day"/></td>
28.    </xsl:template>
29.
30. </xsl:stylesheet>
Example 12-10 makeprop.xsl
 1. <?xml version="1.0"?>
 2.
 3. <xsl:stylesheet
 4.    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 5.    version="1.0">
 6.
 7.    <xsl:output method="text"/>
 8.
 9.    <xsl:template match="/staff/employee">
10. employee.<xsl:value-of select="position()"/>.name=<xsl:value-of
     select="name/text()"/>
11. employee.<xsl:value-of select="position()"/>.salary=<xsl:value-
     of select="salary/text()"/>
12. employee.<xsl:value-of select="position()"/>.hire
     date=<xsl:value-of select="hiredate/@year"/>-<xsl:value-of
     select="hiredate/@month"/>-<xsl:value-of select="hiredate/@day"/>
13.    </xsl:template>
14.
15. </xsl:stylesheet>

javax.xml.transform.TransformerFactory

graphics/api.gif
 

javax.xml.transform.stream.StreamSource

graphics/api.gif
 

javax.xml.transform.sax.SAXSource

graphics/api.gif
 

org.xml.sax.XMLReader

graphics/api.gif
 

javax.xml.transform.dom.DOMResult

graphics/api.gif
 

org.xml.sax.helpers.AttributesImpl

graphics/api.gif
 

CONTENTS